/**
 * 多语言支持功能
 */

// 当前语言
let currentLocale = '';

// 初始化国际化
function initializeI18n() {
    // 获取保存的语言设置，如果没有则使用 Chrome 获取的语言
    chrome.storage.local.get(['locale'], function(result) {
        if (result.locale) {
            currentLocale = result.locale;
        } else {
            // 获取浏览器语言或 Chrome 当前语言
            currentLocale = chrome.i18n.getUILanguage().replace('-', '_');

            // 检查是否支持该语言，目前支持中文、英文和西班牙语
            if (currentLocale.startsWith('zh')) {
                currentLocale = 'zh_CN';
            } else if (currentLocale.startsWith('es')) {
                currentLocale = 'es';
            } else {
                currentLocale = 'en';
            }

            // 保存语言设置
            chrome.storage.local.set({ locale: currentLocale });
        }

        // 应用语言
        applyLocalization();

        // 添加语言切换监听器
        setupLanguageSwitcher();
    });
}

// 应用本地化文本
function applyLocalization() {
    // 获取所有需要本地化的元素
    const elements = document.querySelectorAll('[data-i18n]');

    elements.forEach(element => {
        const key = element.getAttribute('data-i18n');
        let message = fetchTranslation(key, currentLocale);

        if (message) {
            applyTranslation(element, message, key);
        }
    });

    // 更新语言切换器状态
    updateLanguageSwitcherDisplay();
}

// 应用翻译到元素
function applyTranslation(element, translation, key) {
    // 如果是 input 或 textarea，设置 placeholder
    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
        if (element.hasAttribute('placeholder')) {
            element.placeholder = translation;
        }
    } else if (element.tagName === 'BUTTON' && element.id !== 'language-switcher') {
        // 如果是按钮，但不是语言切换按钮，可能有子元素
        const spanElement = element.querySelector('span');
        if (spanElement) {
            spanElement.textContent = translation;
        } else {
            element.textContent = translation;
        }
    } else {
        // 对于其他元素，设置内容
        element.textContent = translation;
    }
}

// 手动获取翻译
function fetchTranslation(key, locale) {
    try {
        // 根据 locale 选择不同的翻译对象
        let translations;
        if (locale === 'zh_CN') {
            translations = {
                "title": "SVG 预览器",
                "subtitle": "粘贴您的 SVG 代码，即时查看效果",
                "editorTab": "编辑器",
                "previewTab": "预览",
                "svgPlaceholder": "在这里粘贴您的 SVG 代码...",
                "previewButton": "预览",
                "pasteButton": "粘贴",
                "copyButton": "复制",
                "clearButton": "清除",
                "cleared": "已清除",
                "noSvgCode": "请输入 SVG 代码",
                "svgPasted": "SVG 代码已粘贴",
                "invalidSvg": "剪贴板内容不是有效的 SVG 代码",
                "clipboardError": "无法访问剪贴板",
                "nothingToCopy": "没有可复制的 SVG 代码",
                "svgCopied": "SVG 代码已复制到剪贴板",
                "copyError": "复制失败",
                "positionReset": "已重置位置",
                "renderError": "渲染错误：",
                "invalidSvgCode": "无效的 SVG 代码",
                "svgFileLoaded": "SVG 文件已加载",
                "dragSvgFile": "请拖放 SVG 文件",
                "exampleLoaded": "已加载示例 SVG",
                "exampleButton": "示例"
            };
        } else if (locale === 'es') {
            translations = {
                "title": "Visor SVG",
                "subtitle": "Pegue su código SVG para verlo al instante",
                "editorTab": "Editor",
                "previewTab": "Vista previa",
                "svgPlaceholder": "Pegue su código SVG aquí...",
                "previewButton": "Vista previa",
                "pasteButton": "Pegar",
                "copyButton": "Copiar",
                "clearButton": "Limpiar",
                "cleared": "Limpiado",
                "noSvgCode": "Por favor ingrese código SVG",
                "svgPasted": "Código SVG pegado",
                "invalidSvg": "El contenido del portapapeles no es un código SVG válido",
                "clipboardError": "No se puede acceder al portapapeles",
                "nothingToCopy": "No hay código SVG para copiar",
                "svgCopied": "Código SVG copiado al portapapeles",
                "copyError": "Error al copiar",
                "positionReset": "Posición restablecida",
                "renderError": "Error de renderizado: ",
                "invalidSvgCode": "Código SVG inválido",
                "svgFileLoaded": "Archivo SVG cargado",
                "dragSvgFile": "Por favor arrastre un archivo SVG",
                "exampleLoaded": "Ejemplo SVG cargado",
                "exampleButton": "Ejemplo"
            };
        } else {
            translations = {
                "title": "SVG Viewer",
                "subtitle": "Paste your SVG code to view it instantly",
                "editorTab": "Editor",
                "previewTab": "Preview",
                "svgPlaceholder": "Paste your SVG code here...",
                "previewButton": "Preview",
                "pasteButton": "Paste",
                "copyButton": "Copy",
                "clearButton": "Clear",
                "cleared": "Cleared",
                "noSvgCode": "Please enter SVG code",
                "svgPasted": "SVG code pasted",
                "invalidSvg": "Clipboard content is not valid SVG code",
                "clipboardError": "Cannot access clipboard",
                "nothingToCopy": "No SVG code to copy",
                "svgCopied": "SVG code copied to clipboard",
                "copyError": "Copy failed",
                "positionReset": "Position reset",
                "renderError": "Render error: ",
                "invalidSvgCode": "Invalid SVG code",
                "svgFileLoaded": "SVG file loaded",
                "dragSvgFile": "Please drag an SVG file",
                "exampleLoaded": "Example SVG loaded",
                "exampleButton": "Example"
            };
        }

        return translations[key];
    } catch (error) {
        console.error('Error fetching translation:', error);
        return null;
    }
}

// 切换语言
function switchLanguage(locale) {
    if (currentLocale !== locale) {
        currentLocale = locale;
        chrome.storage.local.set({ locale: locale }, function() {
            // 应用新语言
            applyLocalization();
        });
    }
}

// 设置语言切换器
function setupLanguageSwitcher() {
    const languageSwitcher = document.getElementById('language-switcher');
    if (languageSwitcher) {
        languageSwitcher.addEventListener('click', function() {
            // 切换语言
            let newLocale;
            switch (currentLocale) {
                case 'en':
                    newLocale = 'zh_CN';
                    break;
                case 'zh_CN':
                    newLocale = 'es';
                    break;
                case 'es':
                    newLocale = 'en';
                    break;
                default:
                    newLocale = 'en';
            }
            switchLanguage(newLocale);
        });

        // 初始设置语言切换器的文本
        updateLanguageSwitcherDisplay();
    }
}

// 更新语言切换器显示
function updateLanguageSwitcherDisplay() {
    const languageSwitcher = document.getElementById('language-switcher');
    if (languageSwitcher) {
        // 根据当前语言更新显示文本
        switch (currentLocale) {
            case 'en':
                languageSwitcher.textContent = 'English';
                break;
            case 'zh_CN':
                languageSwitcher.textContent = '中文';
                break;
            case 'es':
                languageSwitcher.textContent = 'Español';
                break;
            default:
                languageSwitcher.textContent = 'English';
        }
    }
}

// 导出函数
window.i18n = {
    initialize: initializeI18n,
    switchLanguage: switchLanguage,
    getTranslation: function(key) {
        return fetchTranslation(key, currentLocale);
    }
};

// 页面加载完成后初始化国际化
document.addEventListener('DOMContentLoaded', initializeI18n);